import "dart:ui";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:flutter/material.dart";
import "package:flutter/widgets.dart";

Path dashedPath(Path path, List<double> segments) {
  Path dashedPath = Path();
  double distance = 0;
  for (PathMetric pathMetric in path.computeMetrics()) {
    while (distance < pathMetric.length) {
      dashedPath.addPath(
        pathMetric.extractPath(distance, distance + segments[0]),
        Offset.zero,
      );
      distance += segments[0];
      distance += segments[1];
    }
  }
  return dashedPath;
}

class DashedDivider extends StatelessWidget {
  final Color color;
  final Axis direction;
  final EdgeInsetsGeometry? padding;
  final double width;
  final double height;
  final List<double> segments;
  final StrokeCap strokeCap;
  final double strokeWidth;

  const DashedDivider({
    super.key,
    this.color = ThemeVars.colorDivider,
    this.direction = Axis.horizontal,
    this.padding,
    this.width = double.infinity,
    this.height = double.infinity,
    this.segments = const [10, 10],
    this.strokeCap = StrokeCap.round,
    this.strokeWidth = 3,
  }) : assert(segments.length == 2);

  @override
  Widget build(BuildContext context) {
    Widget current = CustomPaint(
      painter: DahsedPainter(
        color: color,
        direction: direction,
        segments: segments,
        strokeCap: strokeCap,
        strokeWidth: strokeWidth,
      ),
      child: SizedBox.fromSize(
        size: direction == Axis.horizontal
            ? Size(width, strokeWidth)
            : Size(strokeWidth, height),
      ),
    );
    if (padding != null) current = Padding(padding: padding!, child: current);
    return current;
  }
}

class DahsedPainter extends CustomPainter {
  final Color color;
  final Axis direction;
  final List<double> segments;
  final StrokeCap strokeCap;
  final double strokeWidth;

  const DahsedPainter({
    required this.color,
    required this.direction,
    required this.segments,
    required this.strokeCap,
    required this.strokeWidth,
  });

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = color
      ..strokeCap = strokeCap
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke;

    bool horizontal = direction == Axis.horizontal;
    double distance = horizontal ? size.width : size.height;
    double offset = strokeWidth / 2;
    Offset a = Offset(horizontal ? 0 : offset, horizontal ? offset : 0);
    Offset b = a + Offset(horizontal ? distance : 0, horizontal ? 0 : distance);

    Path path = Path();
    path.moveTo(a.dx, a.dy);
    path.lineTo(b.dx, b.dy);
    canvas.drawPath(dashedPath(path, segments), paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
